<template>
  <div style="height: calc(100% - 40px)">
    <div class="anmesd">
      <ul class="typeLists f-cb">
        <li
          v-for="(item, index) in typeList"
          :key="index"
          @click="TypeListChange(item)"
          :class="typeActive == item.type ? 'hover' : ''"
        >
          {{ item.name }}
        </li>
      </ul>
      <div v-show="tableList.length == 0" class="zanwu">{{ $t("m.NoData") }}</div>
      <el-table
        v-show="!tableList.length == 0"
        @row-click="cellClicks"
        @row-contextmenu="contextmenu"
        :data="tableList"
        style="width: 100%"
        class="tableAuto"
        :max-height="heightList"
        ref="chatContent"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          min-width="150px"
          :label="$t('quotation.left_list.56hzdc682d00')"
          prop="name"
          class-name="stock_list_left"
        >
          <template slot-scope="scope">
            <div class="first_table">
              <h2 class="stock_list_h2">{{ scope.row.name }}</h2>
              <p class="stock_list_p">
                <img
                  class="type_icon"
                  :src="
                    scope.row.market == 'HKEX'
                      ? HKicon
                      : scope.row.market == 'US'
                      ? USicon
                      : scope.row.market == 'SSE'
                      ? SHicon
                      : SZicon
                  "
                  alt=""
                />
                <span>{{ scope.row.symbol }}</span>
                <!-- <span class="rongzi" v-if="scope.row.isFinance != null && scope.row.isFinance != 0">{{`融`}}</span> -->
                <span class="support">
                  <!-- 支持融资 -->
                  <img
                    :src="require('@/assets/img/icon_zdx.png')"
                    v-if="scope.row.isSell == 0 && scope.row.isFinance == 1"
                  />
                  <!-- 支持融券 -->
                  <img
                    :src="require('@/assets/img/icon_zkx.png')"
                    v-else-if="
                      scope.row.isSell == 1 && scope.row.isFinance == 0
                    "
                  />
                  <!-- 支持融资融券 -->
                  <img
                    :src="require('@/assets/img/icon_rzrqx.png')"
                    v-else-if="
                      scope.row.isFinance == 1 && scope.row.isSell == 1
                    "
                  />
                </span>
                <!-- <span class="kong" v-if="scope.row.isFinance != null &&  scope.row.isSell != 0">{{`空`}}</span> -->
                <img
                  class="warn_icon"
                  v-if="scope.row.isFinance != null && scope.row.warnId != 0"
                  src="@/assets/img/icon_yjls.png"
                  alt=""
                />
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          min-width="90px"
          :label="$t('m.latestPrice')"
          sortable
          prop="latestPrice"
          class-name="stock_list_center"
        >
          <template slot-scope="scope">
            <div
              class="center_atble"
              :class="
                Number(scope.row.gain) > 0
                  ? 'red'
                  : Number(scope.row.gain) == 0
                  ? ''
                  : 'green'
              "
            >
              {{
                Number(scope.row.latestPrice)
                  | toFixed(Number(scope.row.precision))
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          min-width="90px"
          :label="$t('m.quoteChange')"
          sortable
          prop="gain"
          class-name="stock_list_center"
        >
          <template slot-scope="scope">
            <div
              class="last_table"
              :class="
                Number(scope.row.gain) > 0
                  ? 'red'
                  : Number(scope.row.gain) == 0
                  ? ''
                  : 'green'
              "
            >
              {{
                scope.row.gain > 0
                  ? "+" + (scope.row.gain * 100).toFixed(2)
                  : (scope.row.gain * 100).toFixed(2)
              }}%
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="Disclaimers" @click="DisclaimersClick" v-if="KeyNavs == 0">
        {{ $t("quotation.left_list.56hzdc682sw0") }}
      </div>
    </div>
    <disclaimer
      :data="Disclaimerstext"
      :show="disclaimersShow"
      @CloseClick="CloseClicks"
      v-if="disclaimersShow"
    ></disclaimer>
  </div>
</template>
<script>
import Disclaimer from "@/components/quotation/Disclaimers.vue";
import {get_history, post_history, get_optional} from '@/assets/js/API/user.js';
import {get_explain} from '@/assets/js/API/info.js';
export default {
  components: {
    Disclaimer,
  },
  props: ["KeyNavs"],
  data() {
    return {
      tableList: [],
      tableListH: [],
      // 自选参数
      optionSubmit: {
        type: "",
        field: "",
        sort: "",
      },
      HKicon: require("@/assets/img/icon_hk.png"),
      USicon: require("@/assets/img/icon_us.png"),
      SHicon: require("@/assets/img/icon_sh.png"),
      SZicon: require("@/assets/img/icon_sz(1).png"),
      typeList: [
        {
          type: "",
          name: this.$t("quotation.left_list.56hzdc682xg0"),
        },
        {
          type: "HK",
          name: this.$t("quotation.left_list.56hzdc683200"),
        },
        {
          type: "US",
          name: this.$t("quotation.left_list.56hzdc6834w0"),
        },
        {
          type: "CN",
          name: this.$t("quotation.left_list.56hzdc6837s0"),
        },
      ],
      historySubmit: {
        type: "",
        platform: "PC",
        pageSize: 20,
        page: 1,
      },
      heightList: null,
      typeActive: "",
      loading: true,
      Disclaimerstext: "",
      disclaimersShow: false,
      zixuanTime: null, //自选定时器
    };
  },
  mounted() {
    this.zixuan();
    this.$nextTick(function () {
      this.heightList = $(".anmesd").height() - 70;
    });
    var box = this.$refs.chatContent.bodyWrapper;
    box.addEventListener("scroll", this.paperScroll);
    if (this.level.CN) {
      // 沪深行情等级为1，没有其他行情会员时，3秒定时刷新
      if (this.level.CN.level <= 1) {
        if(this.zixuanTime == null) {
          this.zixuanTime = setInterval(() => {
            this.refreshCN();
          }, 5000);
        }
      }
    }
  },
  beforeDestroy() {
    if (this.zixuanTime) {
      clearInterval(this.zixuanTime); //关闭
    }
  },
  methods: {
    paperScroll() {
      var _this = this;
      var box = this.$refs.chatContent.bodyWrapper;
      // 滚动距离
      this.scroll = box.scrollTop;
      // 变量windowHeight是可视区的高度
      this.windowHeight = box.clientHeight || box.clientHeight;
      // 变量scrollHeight是滚动条的总高度
      this.scrollHeight = box.scrollHeight || box.scrollHeight;
      if (
        this.scroll + this.windowHeight == this.scrollHeight &&
        this.tableListH.length >= 20 &&
        this.KeyNavs != 0
      ) {
        _this.historySubmit.page++;
        _this.history();
        // 获取到的不是全部数据 当滚动到底部 继续获取新的数据
      }
    },
    TypeListChange(item) {
      this.typeActive = item.type;
      this.tableList = [];
      if (this.KeyNavs == 0) {
        this.optionSubmit.type = item.type;
      } else {
        this.historySubmit.type = item.type;
        this.historySubmit.page = 1;
      }
    },
    // 自选股列表
    zixuan() {
      let _this = this;
      _this.loading = true;
      if (_this.loading) {
          get_optional(_this.optionSubmit).then(function (res) {
            if (res.code == 1) {
              _this.tableList = [...res.data.list];
              _this.tableList.forEach(function (res) {
                res.latestPrice = parseFloat(res.latestPrice);
                res.gain = parseFloat(res.gain);
              });
              let wsList = _this.addWsList(_this.tableList);
              // 推送列表存在则放入推送队列
              if (wsList.length > 0)
                _this.$store.dispatch("SetZixuanSub", JSON.stringify(wsList));
              _this.loading = false;
            } else {
              _this.$message({
                message: res.msg,
                type: "warning",
              });
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    },
    // 5秒请求沪深接口
    refreshCN() {
      let _this = this;
        get_optional({
            type: "CN",
            field: "gain",
            sort: "DESC",
          }).then((res) => {
          if (res.code == 1) {
            if (res.data.list.length > 0) {
              res.data.list.forEach((item) => {
                for (let i = 0; i < _this.tableList.length; i++) {
                  if (
                    item.symbol == _this.tableList[i].symbol &&
                    item.latestPrice != _this.tableList[i].latestPrice
                  ) {
                    let isBreaths;
                    // 如果股票价格更新了5,4,3次时呼吸灯闪烁2,1,0不闪
                    if (
                      !_this.tableList[i].isBreath ||
                      _this.tableList[i].isBreath == 6
                    )
                      isBreaths = 6;
                    else isBreaths = _this.tableList[i].isBreath;
                    isBreaths = isBreaths - 2;
                    _this.$nextTick(() => {
                      _this.$set(_this.tableList, i, item);
                      _this.$set(_this.tableList[i], "isBreath", isBreaths);
                    });
                    break;
                  }
                }
              });
            }
          }
        })
        .catch((error) => {});
    },
    // 将自选股添加进自选订阅队列
    addWsList(list) {
      let wsList = [];
      list.forEach((item) => {
        let objs = {};
        if (item.market == "SZSE" || item.market == "SSE") {
          // 自选股票为沪深，且等级为2时放入推送
          if (this.level.CN && this.level.CN.level) {
            if (this.level.CN.level == 2) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        } else if (item.market == "HKEX") {
          // 自选股票为港股，且等级为2时放入推送
          if (this.level.HK && this.level.HK.level) {
            if (this.level.HK.level == 2) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        } else if (item.market == "US") {
          // 自选股票为美股，且等级为1时放入推送
          if (this.level.US && this.level.US.level) {
            if (this.level.US.level == 1) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        }
      });
      return wsList;
    },
    // 历史记录列表
    history() {
      let _this = this;
      _this.loading = true;
      if (_this.loading) {
          get_history({
            params: _this.historySubmit,
          }).then(function (res) {
            if (res.code == 1) {
              const template = JSON.parse(
                JSON.stringify(res.data.list).replace(/stockName/g, "name")
              );
              _this.tableListH = template;
              _this.tableList = [..._this.tableList, ...template];
              if (_this.historySubmit.page == 1) {
                _this.tableList = template;
              }
              _this.tableList.forEach(function (res) {
                res.latestPrice = parseFloat(res.latestPrice);
                res.gain = parseFloat(res.gain);
              });
              _this.loading = false;
            } else {
              _this.$message({
                message: res.msg,
                type: "warning",
              });
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    },
    contextmenu(row, column, event) {
      //右点击事件
      console.log(row);
      console.log(column);
      console.log(event);
    },
    cellClicks(row) {
      console.log(row, "Details_data");
      var obj = {
        securityType: row.securityType,
        symbol: row.symbol,
        market: row.market,
      };
      if(row.securityType != 2)
      this.historyAdd(obj);
      this.$emit("Details_dataClick", row);
    },
    // 获取协议,数据免责声明19
    GetDisclaimers() {
      var _this = this;
        get_explain({ pageId: 19 }).then(function (res) {
          if (res.code == 1) {
            _this.Disclaimerstext = res.data;
          } else {
            _this.$message({
              message: res.msg,
              type: "warning",
            });
          }
        });
    },
    DisclaimersClick() {
      // if (this.Disclaimerstext.form == 2) {
      //   window.open(this.Disclaimerstext.pdf);
      // } else {
      //   this.disclaimersShow = true;
      // }
        this.GetDisclaimers();
        this.disclaimersShow = true;
    },
    CloseClicks(msg) {
      this[msg] = false;
    },
    //  股票搜索历史 GET 获取 POST 插入
    async historyAdd(item) {
      var obj = {
        securityType: item.securityType,
        symbol: item.symbol,
        market: item.market,
      };
      const res = await post_history(obj);
      if (res.code != 1) return this.$message.error(res.msg);
      if (this.KeyNavs == 1) {
        if(item.market == "SSE" || item.market == "SZSE")
        {
          this.historySubmit.type = "CN";
        }else if(item.market == "HKEX") this.historySubmit.type = "HK";
        else this.historySubmit.type = "US";
        this.historySubmit.page = 1;
        this.history();
      }
    },
    // 呼吸效果
    tableRowClassName({ row, rowIndex }) {
      if (row.isBreath >= 3) {
        if (row.gain > 0) return "red_breathing";
        else if (row.gain < 0) return "green_breathing";
        else return "";
      }
      return "";
    },
  },
  watch: {
    KeyNavs(val) {
      if (val == 0) {
        this.optionSubmit.type = " ";
        this.zixuan();
        if (this.level.CN) {
          // 沪深行情等级为1，没有其他行情会员时，3秒定时刷新
          if (this.level.CN.level <= 1) {
            if(this.zixuanTime == null) {
              this.zixuanTime = setInterval(() => {
                this.refreshCN();
              }, 5000);
            }
          }
        }
      } else {
        this.historySubmit.type = " ";
        this.historySubmit.page = 1;
        this.history();
        if (this.zixuanTime) {
          clearInterval(this.zixuanTime); //关闭
          this.zixuanTime = null
        }
      }
      this.typeActive = "";
    },
    "optionSubmit.type"(val) {
      this.zixuan();
    },
    "historySubmit.type"(val) {
      this.history();
    },
    "$store.state.index.EarlyWarningNum": {
      handler(val, old) {
        this.zixuan();
      },
      deep: true,
    },
    zixuanList: {
      handler(val, old) {
        var _this = this;
        if (val != "") {
          let data = JSON.parse(val);
          for (let i = 0; i < data.length; i++) {
            if (_this.tableList.length > 0) {
              for (let j = 0; j < _this.tableList.length; j++) {
                if (
                  _this.tableList[j].symbol == data[i].symbol &&
                  _this.tableList[j].market == data[i].market &&
                  _this.tableList[j].securityType == data[i].securityType
                ) {
                  if (data[i].gain && data[i].latestPrice) {
                    if (data[i].latestPrice != _this.tableList[j].latestPrice) {
                      let isBreaths;
                      // 如果股票价格更新了5,4,3次时呼吸灯闪烁2,1,0不闪
                      if (
                        !_this.tableList[j].isBreath ||
                        _this.tableList[j].isBreath == 6
                      )
                        isBreaths = 6;
                      else isBreaths = _this.tableList[j].isBreath;
                      isBreaths--;
                      _this.$nextTick(() => {
                        _this.$set(
                          _this.tableList[j],
                          "latestPrice",
                          data[i].latestPrice
                        );
                        _this.$set(_this.tableList[j], "gain", data[i].gain);
                        _this.$set(_this.tableList[j], "isBreath", isBreaths);
                      });
                    }
                    // 赋值后退出里层循环
                    break;
                  }
                }
              }
            }
          }
        }
      },
      deep: true,
    },
    level: {
      handler(val) {
        if (val != "") {
          if (val.CN) {
            // 沪深行情等级为1，没有其他行情会员时，3秒定时刷新
            if (val.CN.level <= 1) {
              if(this.zixuanTime == null) {
                this.zixuanTime = setInterval(() => {
                  this.refreshCN();
                }, 5000);
              }
            }
          }
        }
      },
      deep: true,
    },
  },
  computed: {
    stockMoreInfo() {
      return this.$store.state.index.stockMoreInfo;
    },
    level() {
      return this.$store.state.index.level;
    },
    zixuanList() {
      return this.$store.state.wsModel.zixuanList;
    },
  },
};
</script>
<style lang="less">
.anmesd {
  height: 100%;
  .typeLists {
    width: 100%;
    border-bottom: 1px solid @LightBorderLine;
    li {
      float: left;
      width: 25%;
      text-align: center;
      cursor: pointer;
      line-height: 29px;
      position: relative;
      color: @fbSix;
      font-size: 12px;
    }
    li.hover,
    li:hover {
      color: @hoverColor !important;
      background-color: transparent !important;
    }
    li.hover:after {
      content: "";
      width: 12px;
      height: 1px;
      background: @hoverColor;
      position: absolute;
      left: 50%;
      bottom: 0px;
      margin-left: -6px;
    }
  }
  .tableAuto {
    max-height: calc(100% - 83px);
    .red_breathing {
      cursor:pointer;
      box-shadow:0 1px 2px rgba(0,0,0,.3);
      -webkit-animation-timing-function:ease-in-out;
      -webkit-animation-name:breathe;
      -webkit-animation-duration:3000ms;
      -webkit-animation-iteration-count: 3;
      -webkit-animation-direction:alternate;
    }
    .green_breathing {
      cursor:pointer;
      box-shadow:0 1px 2px rgba(0,0,0,.3);
      -webkit-animation-timing-function:ease-in-out;
      -webkit-animation-name:breatheGreen;
      -webkit-animation-duration:3000ms;
      -webkit-animation-iteration-count: 3;
      -webkit-animation-direction:alternate;
    }
    @-webkit-keyframes breatheGreen {
      0% {
      opacity:.4;
    }
    100% {
      opacity:.9;
    }
    }
    .el-table__header {
      .header_stock {
        height: 30px;
        .sort-caret.ascending {
          border-bottom-color: @fbSix;
        }
        .sort-caret.descending {
          border-top-color: @fbSix;
        }
      }
      th {
        border-bottom: 1px solid @LightBorderLine;
      }
      .cell {
        font-size: 12px;
        color: @Dark_gray !important;
        font-weight: normal;
      }
      .stock_list_right {
        .cell {
          text-align: right;
        }
      }
      .stock_list_center {
        .cell {
          text-align: center;
        }
      }
      .stock_list_left {
        background: @deepBg;
      }
    }
    .el-table__body {
      cursor: pointer;
      .stock_list_left {
        // background: @deepBg;
        padding-bottom: 0;
        .first_table {
          padding: 6px 0;
        }
        .stock_list_h2 {
          position: relative;
          font-size: 12px;
          color: @fff;
          line-height: 24px;
          white-space: nowrap;
          overflow: hidden;
          height: 24px;
          text-overflow: ellipsis;
        }
        .stock_list_p {
          font-size: 12px;
          color: @fff;
          line-height: 24px;
          position: relative;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .type_icon {
            height: 13px;
            margin-right: 5px;
          }
          .warn_icon {
            width: 16px;
          }
          .rongzi {
            line-height: 14px;
            color: @fbSix;
          }
          .support {
            img {
              width: 14px;
              margin-bottom: 3px;
            }
          }
          .kong {
            color: @fbSix;
          }
          span {
            // float: left;
            font-size: 12px;
            color: @fff;
            // padding: 0 3px;
            display: block;
            height: 16px;
            // margin-top: 2px;
            line-height: 16px;
            margin-right: 5px;
          }
        }
      }
      .stock_list_center {
        .cell {
          color: @fff;
          font-size: 12px;
          text-align: center;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          line-height: 30px;
        }
      }
      .stock_list_right {
        .cell {
          text-align: right;
          h2 {
            font-size: 14px;
            color: @fbSix;
          }
        }
      }
      td {
        border-bottom: 1px solid @LightBorderLine;
      }
    }
    .el-table__fixed::before {
      display: none;
    }
  }
  .Disclaimers {
    text-align: center;
    font-size: 12px;
    height: 36px;
    line-height: 36px;
    color: @fbSix;
    width: 100%;
    cursor: pointer;
    // padding: 10px 0 0;
  }
  .el-loading-mask {
    background: none;
  }
}
</style>